#!/bin/bash

# DevDeploy CV API服务动态启动脚本 (CPU版本)
# 用法: ./start_cv_service_cpu.sh [--classifier <path>] [--segment <path>] [--port <port>]

# 解析参数
CLASSIFIER_MODEL_PATH=""
SEGMENT_MODEL_PATH=""
PORT=8796

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --classifier)
            CLASSIFIER_MODEL_PATH="$2"
            shift 2
            ;;
        --segment)
            SEGMENT_MODEL_PATH="$2"
            shift 2
            ;;
        --port)
            PORT="$2"
            shift 2
            ;;
        *)
            echo "❌ 未知参数: $1"
            echo ""
            echo "用法: $0 [--classifier <path>] [--segment <path>] [--port <port>]"
            echo ""
            echo "参数说明:"
            echo "  --classifier <path>  - 分类模型路径（可选）"
            echo "  --segment <path>     - 分割模型路径（可选）"
            echo "  --port <port>        - 服务端口号（可选，默认8796）"
            echo ""
            echo "注意: 至少需要配置一个模型（分类或分割）"
            echo ""
            echo "示例:"
            echo "  # 只配置分类模型"
            echo "  $0 --classifier ../weights/resnet50_qiu/fullmodel_best.onnx"
            echo ""
            echo "  # 只配置分割模型"
            echo "  $0 --segment ../weights/segment_model.onnx"
            echo ""
            echo "  # 同时配置分类和分割模型"
            echo "  $0 --classifier ../weights/resnet50_qiu/fullmodel_best.onnx --segment ../weights/segment_model.onnx"
            exit 1
            ;;
    esac
done

# 检查至少配置了一个模型
if [ -z "$CLASSIFIER_MODEL_PATH" ] && [ -z "$SEGMENT_MODEL_PATH" ]; then
    echo "❌ 错误: 至少需要配置一个模型（分类或分割）"
    echo "使用 --classifier 指定分类模型，或使用 --segment 指定分割模型"
    exit 1
fi

# 检查模型文件是否存在
if [ -n "$CLASSIFIER_MODEL_PATH" ] && [ ! -f "$CLASSIFIER_MODEL_PATH" ]; then
    echo "❌ 错误: 分类模型文件不存在: $CLASSIFIER_MODEL_PATH"
    exit 1
fi

if [ -n "$SEGMENT_MODEL_PATH" ] && [ ! -f "$SEGMENT_MODEL_PATH" ]; then
    echo "❌ 错误: 分割模型文件不存在: $SEGMENT_MODEL_PATH"
    exit 1
fi

# 确定任务类型
if [ -n "$CLASSIFIER_MODEL_PATH" ] && [ -n "$SEGMENT_MODEL_PATH" ]; then
    # 同时配置了分类和分割模型，使用 cv
    TASK_TYPE="cv"
elif [ -n "$CLASSIFIER_MODEL_PATH" ]; then
    # 只配置了分类模型
    TASK_TYPE="classification"
elif [ -n "$SEGMENT_MODEL_PATH" ]; then
    # 只配置了分割模型
    TASK_TYPE="segmentation"
fi

CONTAINER_NAME="devdeploy-cv-${TASK_TYPE}-cpu-${PORT}"
COMPOSE_FILE="docker-compose.cpu.${TASK_TYPE}.${PORT}.yml"
# CPU版本镜像名称
IMAGE_NAME="devdeploy-cv-api-cpu:latest"

# 模型路径转换为容器内路径
# 处理 ../weights/ 路径，转换为容器内的 /app/weights/ 路径
convert_to_container_path() {
    local model_path=$1
    if [[ "${model_path}" == ../weights/* ]]; then
        # 去掉 ../ 前缀，保留 weights/ 后面的部分
        RELATIVE_PATH="${model_path#../}"
        echo "/app/${RELATIVE_PATH}"
    elif [[ "${model_path}" == weights/* ]]; then
        # 如果已经是 weights/ 开头，直接拼接
        echo "/app/${model_path}"
    else
        # 其他情况，直接拼接（保持向后兼容）
        echo "/app/${model_path}"
    fi
}

CLASSIFIER_MODEL_PATH_IN_CONTAINER=""
if [ -n "$CLASSIFIER_MODEL_PATH" ]; then
    CLASSIFIER_MODEL_PATH_IN_CONTAINER=$(convert_to_container_path "$CLASSIFIER_MODEL_PATH")
fi

SEGMENT_MODEL_PATH_IN_CONTAINER=""
if [ -n "$SEGMENT_MODEL_PATH" ]; then
    SEGMENT_MODEL_PATH_IN_CONTAINER=$(convert_to_container_path "$SEGMENT_MODEL_PATH")
fi

echo "🚀 启动DevDeploy CV API服务 (CPU版本)..."
echo ""
echo "配置信息:"
echo "  - 任务类型: ${TASK_TYPE}"
echo "  - 镜像名称: ${IMAGE_NAME}"
if [ -n "$CLASSIFIER_MODEL_PATH" ]; then
    echo "  - 分类模型路径: ${CLASSIFIER_MODEL_PATH}"
    echo "  - 分类模型容器内路径: ${CLASSIFIER_MODEL_PATH_IN_CONTAINER}"
else
    echo "  - 分类模型: 未配置"
fi
if [ -n "$SEGMENT_MODEL_PATH" ]; then
    echo "  - 分割模型路径: ${SEGMENT_MODEL_PATH}"
    echo "  - 分割模型容器内路径: ${SEGMENT_MODEL_PATH_IN_CONTAINER}"
else
    echo "  - 分割模型: 未配置"
fi
echo "  - 端口: ${PORT}"
echo "  - 容器名称: ${CONTAINER_NAME}"
echo "  - Compose文件: ${COMPOSE_FILE}"
echo ""

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker服务"
    exit 1
fi

echo "✅ 模型文件检查通过"

# 检查端口是否被占用
if netstat -tuln 2>/dev/null | grep -q ":${PORT}"; then
    echo "❌ 端口 ${PORT} 已被占用"
    echo "请使用其他端口"
    exit 1
fi

# 检查容器是否已存在
if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo "⚠️  容器 ${CONTAINER_NAME} 已存在"
    read -p "是否要停止并删除旧容器? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "正在停止旧容器..."
        docker-compose -f ${COMPOSE_FILE} down 2>/dev/null
        docker stop ${CONTAINER_NAME} > /dev/null 2>&1
        docker rm ${CONTAINER_NAME} > /dev/null 2>&1
    else
        echo "❌ 取消启动"
        exit 1
    fi
fi

# SSH端口计算
SSH_HOST_PORT=$((4022 + PORT - 8796))
SSH_CONTAINER_PORT=22

# 模板文件路径（CPU版本）
COMPOSE_TEMPLATE="docker-compose.cv.cpu.template.yml"

# 检查模板文件是否存在
if [ ! -f "${COMPOSE_TEMPLATE}" ]; then
    echo "❌ 模板文件不存在: ${COMPOSE_TEMPLATE}"
    echo "请确保模板文件在正确位置"
    exit 1
fi

# 创建日志目录（如果不存在）
LOG_DIR="./logs"
if [ ! -d "$LOG_DIR" ]; then
    echo "📁 创建日志目录: ${LOG_DIR}"
    mkdir -p "$LOG_DIR"
fi

echo "📝 生成 docker-compose 配置文件: ${COMPOSE_FILE}..."
# 使用 sed 替换模板中的占位符
# 如果模型路径为空，使用空字符串
sed -e "s|{{IMAGE_NAME}}|${IMAGE_NAME}|g" \
    -e "s|{{CONTAINER_NAME}}|${CONTAINER_NAME}|g" \
    -e "s|{{PORT}}|${PORT}|g" \
    -e "s|{{SSH_HOST_PORT}}|${SSH_HOST_PORT}|g" \
    -e "s|{{MODEL_PATH_IN_CONTAINER}}|${CLASSIFIER_MODEL_PATH_IN_CONTAINER}|g" \
    -e "s|{{SEGMENT_MODEL_PATH_IN_CONTAINER}}|${SEGMENT_MODEL_PATH_IN_CONTAINER}|g" \
    "${COMPOSE_TEMPLATE}" > "${COMPOSE_FILE}"

echo "✅ 配置文件已生成"

# 检查Docker镜像是否存在，如果不存在则构建
if ! docker images --format '{{.Repository}}:{{.Tag}}' | grep -q "^${IMAGE_NAME}$"; then
    echo "🔨 构建Docker镜像: ${IMAGE_NAME}..."
    docker build -t ${IMAGE_NAME} -f Dockerfile.cpu .
    if [ $? -ne 0 ]; then
        echo "❌ 镜像构建失败"
        rm -f ${COMPOSE_FILE}
        exit 1
    fi
    echo "✅ 镜像构建完成"
else
    echo "✅ 镜像已存在: ${IMAGE_NAME}"
fi

# 启动服务
echo "🚀 启动服务..."
docker-compose -f ${COMPOSE_FILE} up -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 10

# 检查服务状态
if docker ps | grep -q "${CONTAINER_NAME}"; then
    echo "✅ 服务启动成功！"
    echo ""
    echo "📋 服务信息："
    echo "  - API地址: http://localhost:${PORT}"
    echo "  - 健康检查: http://localhost:${PORT}/health"
    echo "  - API文档: http://localhost:${PORT}/docs"
    echo "  - 配置信息: http://localhost:${PORT}/config"
    echo "  - SSH端口: ${SSH_HOST_PORT}"
    echo ""
    echo "📝 日志文件位置："
    echo "  - 日志文件: ./logs/cv_api_port_${PORT}.log"
    echo "  - 实时查看: tail -f ./logs/cv_api_port_${PORT}.log"
    echo ""
    echo "🔍 查看容器日志: docker-compose -f ${COMPOSE_FILE} logs -f"
    echo "🛑 停止服务: docker-compose -f ${COMPOSE_FILE} down"
    echo "🔄 重启服务: docker-compose -f ${COMPOSE_FILE} restart"
else
    echo "❌ 服务启动失败"
    echo "查看日志: docker-compose -f ${COMPOSE_FILE} logs"
    exit 1
fi
